package cn.tedu.ivoscm.dictoption.service.impl;

import cn.tedu.ivoscm.base.exception.ServiceException;
import cn.tedu.ivoscm.base.response.StatusCode;
import cn.tedu.ivoscm.dict.mapper.DictMapper;
import cn.tedu.ivoscm.dict.pojo.dto.DictQuery;
import cn.tedu.ivoscm.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivoscm.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivoscm.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.ivoscm.dictoption.pojo.entity.DictOption;
import cn.tedu.ivoscm.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivoscm.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    private DictOptionMapper dictOptionMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private RedisTemplate<String, DictOptionVO> redisTemplate;


    @Override
    public List<DictOptionVO> select(DictOptionQuery doq) {
        log.debug("查询字典项业务，参数：{}", doq);
        List<DictOptionVO> list = dictOptionMapper.select(doq);
        return list;
    }

    @Override
    public void save(DictOptionSaveParam dosp) {
        log.debug("保存字典项业务，参数：{}", dosp);
        DictOption _do = new DictOption();
        BeanUtils.copyProperties(dosp, _do);
        if (_do.getId() == null) {
            _do.setCreateTime(new Date());
            dictOptionMapper.insert(_do);
        } else {
            _do.setUpdateTime(new Date());
            dictOptionMapper.update(_do);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("删除字典项业务，参数：{}", id);
        dictOptionMapper.delete(id);
    }

    @Override
    public void deleteByDictId(Long id) {
        log.debug("根据外键字典id删除多个字典项业务，参数：{}", id);
        dictOptionMapper.deleteByDictId(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionsByDictCode(String code) {
        log.debug("根据字典code查询字典项业务，参数：{}", code);
        ListOperations<String, DictOptionVO> ops = redisTemplate.opsForList();
        Long len = ops.size(code);
        if (len == null || len == 0) {
            DictQuery dq = new DictQuery();
            dq.setCode(code);
            if (dictMapper.select(dq) == null || dictMapper.select(dq).isEmpty()) {
                throw new ServiceException(StatusCode.DATA_UNEXISTS);
            }
            List<DictOptionVO> list = dictOptionMapper.selectDictOptionsByDictCode(code);
            for(DictOptionVO d : list) {
                ops.rightPush(code, d);
            }
            return list;
        } else {
            return ops.range(code, 0, -1);
        }
    }
}
